/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年10月5日 上午11:04:18
 */
package com.absir.appserv.system.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.absir.appserv.configure.JConfigureUtils;
import com.absir.appserv.system.bean.proxy.JiUserBase;
import com.absir.appserv.system.configure.JAnzhiConfigure;
import com.absir.appserv.system.helper.HelperClient;
import com.absir.appserv.system.helper.HelperJson;
import com.absir.bean.inject.value.Bean;
import com.anzhi.util.Base64;
import com.anzhi.util.Des3Util;

/**
 * @author absir
 *
 */
@Bean
public class AnzhiService implements IdentityService {

	/** ANZHI_CONFIGURE */
	public static final JAnzhiConfigure ANZHI_CONFIGURE = JConfigureUtils.getConfigure(JAnzhiConfigure.class);

	/** PLAT_FORM_NAME */
	public static final String PLAT_FORM_NAME = "Anzhi";

	/** queryLoginUrl */
	private String queryLoginUrl = "http://user.anzhi.com/web/api/sdk/third/1/queryislogin";

	public static class LoginData {

		public String sc;

		public String st;

		public String msg;

	}

	public static class LoginDataMessage {

		public String uid;

	}

	/** DATE_FORMAT */
	public static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmssSSS");

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.appserv.system.service.IdentityService#getUserBase(java.lang
	 * .String[])
	 */
	@Override
	public JiUserBase getUserBase(String[] parameters) {
		if (parameters.length == 2) {
			String sid = parameters[1];
			String sign = Base64.encodeToString(ANZHI_CONFIGURE.getMerchantKey() + sid + ANZHI_CONFIGURE.getAppSecrect());
			LoginData loginData = HelperClient.openConnection(queryLoginUrl + "?appkey=" + ANZHI_CONFIGURE.getMerchantKey()
					+ "&sid=" + sid + "&sign=" + sign + "&time=" + DATE_FORMAT.format(new Date()), false, null, LoginData.class);
			if (loginData != null && loginData.sc.equals("1")) {
				String msg = Des3Util.decrypt(loginData.msg, ANZHI_CONFIGURE.getMerchantKey());
				LoginDataMessage dataMessage = HelperJson.decodeNull(msg, LoginDataMessage.class);
				if (dataMessage != null) {
					return SecurityService.ME.openUserBase(dataMessage.uid, null, PLAT_FORM_NAME);
				}
			}
		}

		return null;
	}
}
